import React, { useState, useMemo, useRef, useEffect } from 'react';
import { Modal } from 'antd';
import { ModalProps as AModalProps } from 'antd/lib/modal';
import classNames from 'classnames';
import Icon from './../icon/Icon';
import styles from './modal.module.scss';

interface ModalProps extends AModalProps {
  defaultFull?: boolean;
  showFullIcon?: boolean;
  fullToggle?(visible: boolean): void;
  children?: React.ReactNode
}

export default ({
  showFullIcon = true,
  fullToggle,
  title,
  width,
  defaultFull,
  ...baseProps
}: ModalProps) => {
  const [isFull, setIsFull] = useState(false);

  useEffect(() => {
    if(typeof defaultFull === 'boolean') setIsFull(defaultFull);
  }, [defaultFull]);

  const _width = useMemo(() => {
    if (!showFullIcon || !isFull) return width;

    return `calc(100vw - ${sessionStorage.collapsed === '1' ? '60px' : '240px'})`
  }, [isFull, width, showFullIcon]);

  const classNameExtra = {
    [styles.fullModal]: showFullIcon && isFull,
    [styles.fullModalCollapsed]: showFullIcon && isFull && sessionStorage.collapsed === '1',
  }

  if (baseProps.className) {
    classNameExtra[baseProps.className] = true
  }

  return (
    <Modal
      centered
      maskClosable={false}
      {...baseProps}
      width={_width}
      className={classNames(styles.modal, classNameExtra)}
      title={
        showFullIcon ? (
          <div className={styles.title}>
            <span>{title}</span>
            <Icon
              onClick={() => {
                setIsFull(!isFull);
                setTimeout(() => fullToggle?.(!isFull), 10)
              }}
              className={styles.fullIcon}
              icon={isFull ? '\ue69a' : '\ue699'} />
          </div>
        ) : title
      } />
  )
}